<extend name="layout/main" />

<block name="HEADER">
   <style type="text/css">
    	.layui-col-xs3 { width: 300px; }
		.layui-col-xs3 h1 { flex: 1;  }
		.layui-col-xs3 .layui-btn-sm { margin-top: 7px; }
		.layui-col-xs9 { width: calc(100% - 300px); }
		#tree {
			height: calc(100% - 40px);
			border: 1px solid #e6e6e6;
			-webkit-box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.1);
			box-shadow: 2px 0px 2px 0px rgba(0, 0, 0, 0.1);
			overflow: auto;
		}
		.panel-heading { height: 45px; }
		.layui-row { height: 100%; }
		.layui-row>div { height: 100%; }
		#content_tpl{
			height: calc(100% - 55px);overflow: auto;padding: 20px;
		}
		.pictrueList{
			float: left;
			margin-right: 10px;
			margin-bottom: 10px;
			position: relative;
		}
		.pictrueList .number{
			display: none;
			background: red;
			border-radius:100%;
			padding: 3px 5px;
		    font-size: 10px;
		    line-height: 1;
		    color: #fff;
		}
		.pictrueList.on .number{
			display: block;
		    position: absolute;
		    right: 15px;
		    top: 5px;
		}
		.pictrueList img{
			width: 100px;
			height: 100px;
		}
		.pictrueList:hover img{
		    border: 1px solid #b9b9b9;
		}
		.pictrueList.on img {
		    border: 2px solid #5fb878;
		}
		.pictrueList .name{
			width: 80px;
			overflow: hidden;
			white-space: nowrap; 
			text-overflow: ellipsis;
			line-height: 24px;
		}
		.pictrueList .edit{
			cursor: pointer;
		    position: absolute;
		    bottom: 3px;
		    right: 0;
		    font-size: 20px;
		    display: none;
		}
		.pictrueList:hover .edit{
			display: block;
		}
        .w_content{
            background: #FFFFFF !important;
            padding: 0 !important;
        }
    </style>
</block>

<block name="CONTENT">
    
    <div class="wrapper">
        <div class="layui-row">
            <div class="layui-col-xs3" >
                <div class="panel-heading" style="display: flex;">
                    <h1>文件目录（分类）</h1>
                </div>
                <div id="tree"></div>
            </div>
            <div class="layui-col-xs9">
                <div class="panel-heading" >
                    <control:search id="gallerySearchs" />
                </div>
                <div class="content" style="padding: 0;">
                	<div id="content_tpl"></div>
                	<div id="page1" style="padding:0 20px;width: 100%;"></div>
                </div>    
            </div>
        </div>
    </div>
    
    <!--授权列表模板-->
    <script type="text/html" id="pictrueList_tpl">
    	{{each list as val }}
        <div class="pictrueList">
			<p class="number">0</p>
			<img data-src="{{val.file_path}}" data-id="{{val.file_id}}" src="/admin/soft/upload/downloadHandler?file_id={{val.file_id}}&size=200" >
			<p class="name">{{val.file_name}}</p>
			<i class="iconfont edit">&#xe621;</i>
		</div>
		{{/each}}
		{{if list.length == 0}}
			<div style="display: table;width: 100%; height: 100%;color: #a0a0a0;">
				<div style="text-align: center; vertical-align: middle;display: table-cell;">暂无数据</div>
			</div>
		{{/if}}
    </script>
    
</block>

<block name="FOOTER">
   <script type="text/javascript">
   	var page = (function(ns){
	
		var tree;
	 	
	    //页面初始化
	    ns.init=function(){
	        ns.initTree();
	        ns.initUpload();
	    }
	    
	    //初始化树
	    ns.initTree=function(){
	    	tree = layui.tree.render({
	            elem: '#tree' ,
	            textField:"name",
	            idField:"id",
	            parentField:'pid',
	            data:'/admin/soft/upload_classify/getTree ',
	            isList:true,                         //是否列表结构数据，如果是，idField，parentField 必填
	            expandNode:2,                	//可选，默认展开的节点，字符串
	            showCheckbox: false,  		//是否显示复选框
	            accordion: false, 				//是否开启手风琴模式
	            showIcon:function(e){       //显示图标，可为true
	            	return e.pid == 0 ? "&#xe6a8;" : '&#xe608;';
	            },
	            treeMenu:[                           //可选，存在时则显示更多按钮
	                {title:"新增",onClick:"page.addNode()",enable:function(e){
	                	return 1;
	                }},
	                {title:"编辑",onClick:"page.editNode()",enable:function(e){
	                	return 1
	                }},
	                {title:"删除",onClick:"page.removeNode()",enable:function(e){
	                	return e.pid != 0
	                }}
	            ],
	            loadSuccess:function(data){  //加载成功
	                data[0] && tree.selectNode("id",data[0].id);
	            },
	            selectedNode: function(obj){ // 选中节点
	            	var ids = $.map( tree.getAllChildNodes(), function(h) { return h.id; }).join(',');
	            	ns.query(ids);
	            },
	        });
	    }
	    
	    //新增节点
	    ns.addNode=function(){
	        var  node = tree.getThisNode(); 
	        layer.prompt({
	            title:'请输入文件名称',
	            formType: 3,
	            offset: '25%'
	        }, function(text, index){
	        	var param = { 
	            	pid: node.id, 
	            	name:text 
	           };
	            $.ajaxs("/admin/soft/upload_classify/add",param).then(function(res){
	                param.id= res.data;
	                tree.addNode(param,node);
	                $.toast(1,"成功新增！");
	            });
	            layer.close(index);
	        });
	    }
	    
	    //编辑节点
	    ns.editNode=function(){
	        var  node = tree.getThisNode(); 
	        layer.prompt({
	            title:'重命名',
	            formType: 3,
	            offset: '25%',
	            value:node.org_name
	        }, function(text, index){
	            var param={id:node.id,name:text,pid:node.pid}
	            $.ajaxs("/admin/soft/upload_classify/edit",param,function(res){
	                tree.setNodeText(node,text);
	                $.toast(1,"成功更新！");
	            });
	            layer.close(index);
	        });
	    }
	    
	    //删除节点
	    ns.removeNode=function(){
	        var  node = tree.getThisNode();
	        var ids = $.map( tree.getAllChildNodes(node), function(h) { return h.id;}).join(',');
	        $.confirm('确定删除【'+node.name+'】?',function(index){
	            $.ajaxs("/admin/soft/upload_classify/delete",{ids:ids},function(res){
	                tree.removeNode(node);
	                $.toast(1,"成功删除！");
	            });
	            layer.close(index);
	        });
	    }
	    
	    //查询
	    ns.query =function(classify_ids,pages){
			if(!$.isArray(classify_ids)){
				ns.classify_ids = classify_ids || ns.classify_ids || '0';
			}
	    	ns.pages = pages || ns.pages || { curr:1, limit:50};
	    	$.ajaxs('/admin/soft/upload/getClassifyFileList',{
	    		classify_ids:ns.classify_ids
	    		,name:gallerySearchs.getData('name')
	    		,page:ns.pages.curr
	    		,limit: ns.pages.limit
	    	}).then(function(res){
	    		var html = template("pictrueList_tpl",{list:res.data.list});
	    		$('#content_tpl').html( html );
	    		ns.initEvent();
			  	layui.laypage.render({
			    	elem: 'page1'
			    	,curr: ns.pages.curr || 1
			    	,limit:ns.pages.limit
			    	,count: res.data.count //数据总数
			    	,first: '首页'
				    ,last: '尾页'
				    ,layout: ['prev','page', 'next', 'count']
			    	,jump: function(obj){
			    		if(obj.curr != ns.pages.curr) ns.query(classify_ids,obj);
	    			}
			  	});
	    	});
	    }
	    
	    //初始化点击事件
	    ns.initEvent = function(){
	    	//选中
	    	$(".pictrueList").unbind('click').click(function(){
	    		if( $(this).is('.on') ){
	    			var max =  Math.max.apply(Math,$.map($(".pictrueList.on .number"),function(h){
		    			return Number($(h).text() || 0);
		    		}));
	    			$(this).removeClass('on');
	    			var  num = $(this).find('.number').text();
	    			if( num != max ){
	    				$.each($(".pictrueList.on .number"),function(k,h){
	    					var n = $(h).text() -1; 
	    					if( n >= num)  $(h).text( n < 1 ? 1 :  n );
			    		});
	    			}
	    			$(this).find('.number').text(0);
	    		}else{
	    			$(this).addClass('on');
	    			var max =  Math.max.apply(Math,$.map($(".pictrueList.on .number"),function(h){
		    			return Number($(h).text() || 0);
		    		}));
	    			$(this).find('.number').text(max+1);
	    		}
	    	});
	    	//更新名称
	    	$(".pictrueList .edit").unbind('click').click(function(e){
	    		e.stopPropagation();
	    		var $th = $(this);
	    		var file_id = $th.parent('.pictrueList').find('img').attr('data-id');
		        layer.prompt({
		            title:'文件重命名',
		            formType: 3,
		            offset: '25%',
		            value: $th.parent('.pictrueList').find('.name').text()
		        }, function(text, index){
		            $.ajaxs("/admin/soft/upload/updateName",{
		            	name:text,
		            	file_id: file_id
		            },function(res){
						$th.parent('.pictrueList').find('.name').text(text);
		                $.toast(1,"成功更新！");
		            });
		            layer.close(index);
		        });
	    	});
	    	
	    }
	    
	    //删除文件
	    ns.delFile = function(){
	    	var ids =  $.map($(".pictrueList.on img"),function(h){
    			return Number($(h).attr('data-id') || 0);
    		}).join(',');
    		if(!ids) return $.toast(0,'请选择文件！');
    		$.confirm('不可恢复，确认删除？',function(){
    			$.ajaxs('/admin/soft/upload/deleteFile',{
		    		fileIds:ids
		    	}).then(function(res){
		    		$.toast(1,'已删除！');
		    		ns.query();
		    	});
    		});
	    }
	    
	    //上传
	    ns.initUpload = function(){
			var  uploadObj = layui.uploads.init({
                id: 'upload',					        		//必填，附件主键
                fkGuid: 'sdd' || 'layui-form-item-img-upload',//必填，附件主键
                ywName: '系统文件',  
                fkType: '系统分类',	      
                multiple:false,                                        
                maxCount:1,
                actionCode:window.__mode || 0,         //按钮权限 0/1/2/3
                createBtn:false,
                accept:'images'              //允许上传的文件,images,file,video（视频）、audio（音频）
        	});
        	uploadObj.uploadBefore = function(data){
        		data.classify_id = tree.getSelectedNode()['id'];
        		return data;
        	}
        	uploadObj.uploadSuccess(function(res){
        		$.toast(1,'已上传！');
		    	ns.query();
        	});
	    }
	    
	    //确认选择
	    ns.confirm = function(){
	    	var arr =  $.map( $(".pictrueList.on img") ,function(h){
	    		return {
	    			index: $(h).parents('.pictrueList').find('.number').text(),
	    			src: $(h).attr('data-src') || ''
	    		};
	    	});
    		var data = arr.sort(function(a, b){ return a.index - b.index; });
    		if(!data[0]) return $.toast(0,'请选择文件！');
    		if(opener.galleryUploadsCallback){
    			opener.galleryUploadsCallback(data);
    		}
    		$.close();
	    }
	    
	    
	    return ns;
	}({}));
	
	$(function(){ page.init();  })
   </script>
</block>



